
const db = require('db');
const { toUpdate } = require('tools/sqlString');

module.exports = async ctx => {
    const { connection, run } = db.init();
    await run('BEGIN'); // 开始事务
    try {
        const id = ctx.params.id;
        const body = ctx.request.body;
        await update(id, body, run);
        await run('COMMIT');
        ctx.status = 200;
    } catch (error) {
        await run('ROLLBACK');
        ctx.status = 500;
        console.log(error);
        ctx.body = error
    }
    connection.end();
}

async function update(id, body, run) {
    const sql = toSqlString(id, body);
    const result = await run(sql);
    if (result.err) {
        throw result.err
    }
}

function toSqlString(id, body) {
    const sql = `
        UPDATE client 
        SET ${toUpdate(body)}
        WHERE id = ${id}
    `;
    return sql;
}